#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <sstream>

#include "Log.hpp"

using namespace My_Log;

const std::string sepline = "\r\n";
const std::string sepheard = ": ";

class HttpRequest
{
public:
    HttpRequest()
    {
    }

    void Deserialize(std::string &req)
    {
        // 解析状态行
        int pos = req.find(sepline);
        if (pos == std::string::npos)
        {
            LOG(LogLevel::WARNING) << "find err!";
            return;
        }
        std::stringstream ss(req.substr(0, pos));
        req.erase(0, pos + sepline.size());
        ss >> _method >> _path >> _ver;
        LOG(LogLevel::DEBUG) << "  #  " << _method << "  #  " << _path << "  #  " << _ver;

        // 解析报头
        while (true)
        {
            //解析报头中的一行
            int p1 = req.find(sepline);
            if(p1 == std::string::npos) 
            {
                LOG(LogLevel::WARNING) << "find err";
                return;
            }
            std::string line = req.substr(0, p1);
            req.erase(0, p1 + sepline.size());

            //遇到空行跳出循环
            if (line.empty())
                break;

            //一行中的kv值
            int p2 = line.find(sepheard);
            if(p2 == std::string::npos) 
            {
                LOG(LogLevel::WARNING) << "find err";
                return;
            }
            std::string key = line.substr(0, p2);
            line.erase(0, p2 + sepheard.size());
            _heardkv.insert(std::pair<std::string, std::string>(key, line));
        }

        // 空行
        _empline = sepline;

        // 正文
        _body = req;

        LOGPrint();
    }

    void LOGPrint()
    {
        LOG(LogLevel::DEBUG) << "method: " << _method;
        LOG(LogLevel::DEBUG) << "path: " << _path;
        LOG(LogLevel::DEBUG) << "ver: " << _ver;

        for(auto &h : _heardkv)
        {
            LOG(LogLevel::DEBUG) << h.first << "-----" << h.second;
        }
        LOG(LogLevel::DEBUG) << "empline: " << _empline;
        LOG(LogLevel::DEBUG) << "body: " << _body;
    }

    ~HttpRequest()
    {
    }

private:
    // 客户端发来的http请求解析后的数据
    std::string _method;
    std::string _path;
    std::string _ver;
    std::unordered_map<std::string, std::string> _heardkv;
    std::string _empline;
    std::string _body;
};

class HttpResponse
{
};